package org.jeecg.modules.nurse_user_bill.controller;

import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.query.QueryGenerator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;

import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.nurse_user_bill.entity.NurseUserBillDetail;
import org.jeecg.modules.nurse_user_bill.entity.NurseUserBillInvoice;
import org.jeecg.modules.nurse_user_bill.entity.NurseUserBill;
import org.jeecg.modules.nurse_user_bill.service.INurseUserBillService;
import org.jeecg.modules.nurse_user_bill.service.INurseUserBillDetailService;
import org.jeecg.modules.nurse_user_bill.service.INurseUserBillInvoiceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * @Description: 用户发票
 * @Author: jeecg-boot
 * @Date: 2024-06-04
 * @Version: V1.0
 */
@Api(tags = "用户发票")
@RestController
@RequestMapping("/nurse_user_bill/nurseUserBill")
@Slf4j
public class NurseUserBillController extends JeecgController<NurseUserBill, INurseUserBillService> {

    @Autowired
    private INurseUserBillService nurseUserBillService;

    @Autowired
    private INurseUserBillDetailService nurseUserBillDetailService;

    @Autowired
    private INurseUserBillInvoiceService nurseUserBillInvoiceService;


    /*---------------------------------主表处理-begin-------------------------------------*/

    /**
     * 分页列表查询
     *
     * @param nurseUserBill
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "用户发票-分页列表查询")
    @ApiOperation(value = "用户发票-分页列表查询", notes = "用户发票-分页列表查询")
    @GetMapping(value = "/list")
    @PermissionData(pageComponent = "nurse/nurse_user_bill/NurseUserBillList")
    public Result<IPage<NurseUserBill>> queryPageList(NurseUserBill nurseUserBill,
                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                      HttpServletRequest req) {
        QueryWrapper<NurseUserBill> queryWrapper = QueryGenerator.initQueryWrapper(nurseUserBill, req.getParameterMap());
        Page<NurseUserBill> page = new Page<NurseUserBill>(pageNo, pageSize);
        IPage<NurseUserBill> pageList = nurseUserBillService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param nurseUserBill
     * @return
     */
    @AutoLog(value = "用户发票-添加")
    @ApiOperation(value = "用户发票-添加", notes = "用户发票-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody NurseUserBill nurseUserBill) {
        nurseUserBillService.save(nurseUserBill);
        return Result.OK("添加成功`！");
    }

    /**
     * 编辑
     *
     * @param nurseUserBill
     * @return
     */
    @AutoLog(value = "用户发票-编辑")
    @ApiOperation(value = "用户发票-编辑", notes = "用户发票-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody NurseUserBill nurseUserBill) {
        nurseUserBillService.updateById(nurseUserBill);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "用户发票-通过id删除")
    @ApiOperation(value = "用户发票-通过id删除", notes = "用户发票-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        nurseUserBillService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "用户发票-批量删除")
    @ApiOperation(value = "用户发票-批量删除", notes = "用户发票-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.nurseUserBillService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, NurseUserBill nurseUserBill) {
        return super.exportXls(request, nurseUserBill, NurseUserBill.class, "用户发票");
    }

    /**
     * 导入
     *
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, NurseUserBill.class);
    }
    /*---------------------------------主表处理-end-------------------------------------*/


    /*--------------------------------子表处理-用户发票明细-begin----------------------------------------------*/

    /**
     * 通过主表ID查询
     *
     * @return
     */
    //@AutoLog(value = "用户发票明细-通过主表ID查询")
    @ApiOperation(value = "用户发票明细-通过主表ID查询", notes = "用户发票明细-通过主表ID查询")
    @GetMapping(value = "/listNurseUserBillDetailByMainId")
    public Result<IPage<NurseUserBillDetail>> listNurseUserBillDetailByMainId(NurseUserBillDetail nurseUserBillDetail,
                                                                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                              HttpServletRequest req) {
        QueryWrapper<NurseUserBillDetail> queryWrapper = QueryGenerator.initQueryWrapper(nurseUserBillDetail, req.getParameterMap());
        Page<NurseUserBillDetail> page = new Page<NurseUserBillDetail>(pageNo, pageSize);
        IPage<NurseUserBillDetail> pageList = nurseUserBillDetailService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param nurseUserBillDetail
     * @return
     */
    @AutoLog(value = "用户发票明细-添加")
    @ApiOperation(value = "用户发票明细-添加", notes = "用户发票明细-添加")
    @PostMapping(value = "/addNurseUserBillDetail")
    public Result<String> addNurseUserBillDetail(@RequestBody NurseUserBillDetail nurseUserBillDetail) {
        nurseUserBillDetailService.save(nurseUserBillDetail);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param nurseUserBillDetail
     * @return
     */
    @AutoLog(value = "用户发票明细-编辑")
    @ApiOperation(value = "用户发票明细-编辑", notes = "用户发票明细-编辑")
    @RequestMapping(value = "/editNurseUserBillDetail", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> editNurseUserBillDetail(@RequestBody NurseUserBillDetail nurseUserBillDetail) {
        nurseUserBillDetailService.updateById(nurseUserBillDetail);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "用户发票明细-通过id删除")
    @ApiOperation(value = "用户发票明细-通过id删除", notes = "用户发票明细-通过id删除")
    @DeleteMapping(value = "/deleteNurseUserBillDetail")
    public Result<String> deleteNurseUserBillDetail(@RequestParam(name = "id", required = true) String id) {
        nurseUserBillDetailService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "用户发票明细-批量删除")
    @ApiOperation(value = "用户发票明细-批量删除", notes = "用户发票明细-批量删除")
    @DeleteMapping(value = "/deleteBatchNurseUserBillDetail")
    public Result<String> deleteBatchNurseUserBillDetail(@RequestParam(name = "ids", required = true) String ids) {
        this.nurseUserBillDetailService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "/exportNurseUserBillDetail")
    public ModelAndView exportNurseUserBillDetail(HttpServletRequest request, NurseUserBillDetail nurseUserBillDetail) {
        // Step.1 组装查询条件
        QueryWrapper<NurseUserBillDetail> queryWrapper = QueryGenerator.initQueryWrapper(nurseUserBillDetail, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<NurseUserBillDetail> pageList = nurseUserBillDetailService.list(queryWrapper);
        List<NurseUserBillDetail> exportList = null;

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //此处设置的filename无效,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.FILE_NAME, "用户发票明细");
        mv.addObject(NormalExcelConstants.CLASS, NurseUserBillDetail.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("用户发票明细报表", "导出人:" + sysUser.getRealname(), "用户发票明细"));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 导入
     *
     * @return
     */
    @RequestMapping(value = "/importNurseUserBillDetail/{mainId}")
    public Result<?> importNurseUserBillDetail(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<NurseUserBillDetail> list = ExcelImportUtil.importExcel(file.getInputStream(), NurseUserBillDetail.class, params);
                for (NurseUserBillDetail temp : list) {
                    temp.setBillId(mainId);
                }
                long start = System.currentTimeMillis();
                nurseUserBillDetailService.saveBatch(list);
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                return Result.OK("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-用户发票明细-end----------------------------------------------*/

    /*--------------------------------子表处理-用户电子发票-begin----------------------------------------------*/

    /**
     * 通过主表ID查询
     *
     * @return
     */
    //@AutoLog(value = "用户电子发票-通过主表ID查询")
    @ApiOperation(value = "用户电子发票-通过主表ID查询", notes = "用户电子发票-通过主表ID查询")
    @GetMapping(value = "/listNurseUserBillInvoiceByMainId")
    public Result<IPage<NurseUserBillInvoice>> listNurseUserBillInvoiceByMainId(NurseUserBillInvoice nurseUserBillInvoice,
                                                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                                HttpServletRequest req) {
        QueryWrapper<NurseUserBillInvoice> queryWrapper = QueryGenerator.initQueryWrapper(nurseUserBillInvoice, req.getParameterMap());
        Page<NurseUserBillInvoice> page = new Page<NurseUserBillInvoice>(pageNo, pageSize);
        IPage<NurseUserBillInvoice> pageList = nurseUserBillInvoiceService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param nurseUserBillInvoice
     * @return
     */
    @AutoLog(value = "用户电子发票-添加")
    @ApiOperation(value = "用户电子发票-添加", notes = "用户电子发票-添加")
    @PostMapping(value = "/addNurseUserBillInvoice")
    public Result<String> addNurseUserBillInvoice(@RequestBody NurseUserBillInvoice nurseUserBillInvoice) {
        NurseUserBill nurseUserBill = nurseUserBillService.getOne(new QueryWrapper<NurseUserBill>().eq("order_id", nurseUserBillInvoice.getOrderId()));
        nurseUserBillInvoice.setBillId(nurseUserBill.getId());
        nurseUserBillInvoice.setTotalPrice(nurseUserBill.getAmt());
        nurseUserBillInvoiceService.save(nurseUserBillInvoice);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param nurseUserBillInvoice
     * @return
     */
    @AutoLog(value = "用户电子发票-编辑")
    @ApiOperation(value = "用户电子发票-编辑", notes = "用户电子发票-编辑")
    @RequestMapping(value = "/editNurseUserBillInvoice", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> editNurseUserBillInvoice(@RequestBody NurseUserBillInvoice nurseUserBillInvoice) {
        nurseUserBillInvoiceService.updateById(nurseUserBillInvoice);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "用户电子发票-通过id删除")
    @ApiOperation(value = "用户电子发票-通过id删除", notes = "用户电子发票-通过id删除")
    @DeleteMapping(value = "/deleteNurseUserBillInvoice")
    public Result<String> deleteNurseUserBillInvoice(@RequestParam(name = "id", required = true) String id) {
        nurseUserBillInvoiceService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "用户电子发票-批量删除")
    @ApiOperation(value = "用户电子发票-批量删除", notes = "用户电子发票-批量删除")
    @DeleteMapping(value = "/deleteBatchNurseUserBillInvoice")
    public Result<String> deleteBatchNurseUserBillInvoice(@RequestParam(name = "ids", required = true) String ids) {
        this.nurseUserBillInvoiceService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "/exportNurseUserBillInvoice")
    public ModelAndView exportNurseUserBillInvoice(HttpServletRequest request, NurseUserBillInvoice nurseUserBillInvoice) {
        // Step.1 组装查询条件
        QueryWrapper<NurseUserBillInvoice> queryWrapper = QueryGenerator.initQueryWrapper(nurseUserBillInvoice, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<NurseUserBillInvoice> pageList = nurseUserBillInvoiceService.list(queryWrapper);
        List<NurseUserBillInvoice> exportList = null;

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //此处设置的filename无效,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.FILE_NAME, "用户电子发票");
        mv.addObject(NormalExcelConstants.CLASS, NurseUserBillInvoice.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("用户电子发票报表", "导出人:" + sysUser.getRealname(), "用户电子发票"));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 导入
     *
     * @return
     */
    @RequestMapping(value = "/importNurseUserBillInvoice/{mainId}")
    public Result<?> importNurseUserBillInvoice(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<NurseUserBillInvoice> list = ExcelImportUtil.importExcel(file.getInputStream(), NurseUserBillInvoice.class, params);
                for (NurseUserBillInvoice temp : list) {
                    temp.setBillId(mainId);
                }
                long start = System.currentTimeMillis();
                nurseUserBillInvoiceService.saveBatch(list);
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                return Result.OK("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-用户电子发票-end----------------------------------------------*/


}
